<template>
  <view class="page-container">
    <view class="login-container" v-if="!isLoggedIn">
      <view class="login-btn" @click="handleLogin">
        <text>微信一键登录</text>
      </view>
    </view>

    <!-- 登录后显示的用户信息 -->
    <view class="user-info" v-else>
      <image class="avatar" :src="userInfos.avatarUrl" />
      <view class="nickname">{{ userInfos.nickName }}</view>
    </view>

    <!-- 菜单列表 -->
    <view class="menu-list" :class="{ 'disabled-menu': !isLoggedIn }">
      <view 
        class="menu-item" 
        v-for="(item, index) in menuItems" 
        :key="index" 
        :class="{ 'disabled-item': !isLoggedIn && item.text !== '激活题库' }"
        @click="handleMenuClick(item)"
      >
        <view class="menu-content">
          <!-- 左侧图标 -->
          <view class="menu-icon">
            <IconFont :name="item.icon" size="35" :color="getIconColor(item)" />
          </view>
          <!-- 中间文字 -->
          <text class="menu-text" :class="{ 'disabled-text': !isLoggedIn && item.text !== '激活题库' }">
            {{ item.text }}
          </text>
          <!-- 右侧箭头 -->
          <view class="menu-arrow">
            <IconFont :name=arrows size="28" :color="getIconColor(item)" />
          </view>
        </view>
        <!-- 分隔线（最后一项不加） -->
        <view class="divider" v-if="index !== menuItems.length - 1"></view>
      </view>
    </view>

    <!-- 未登录提示 -->
    <view v-if="!isLoggedIn" class="login-tip">
      <text class="tip-text">登录后可使用更多功能</text>
    </view>

    <!-- 新增底部导航栏 -->
    <view class="tab-bar">
      <view class="tab-item" :class="{ active: activeTab === 'index' }" @click="switchTab('index')">
        <image :src="photoH" class="tab-icon" />
        <text class="tab-text">首页</text>
      </view>
      <view class="tab-item" :class="{ active: activeTab === 'profile' }" @click="switchTab('profile')">
        <image :src="photoP" class="tab-icon" />
        <text class="tab-text">个人中心</text>
      </view>
    </view>

  </view>
</template>

<script setup>
import { IconFont } from '@nutui/icons-vue'
import { ref, onMounted ,onUnmounted} from 'vue'
import config from '../../config'
import Taro from '@tarojs/taro'
//菜单图标

const activity = ref(require('../../assets/激活.png'));
const user = ref(require('../../assets/证件.png'));
const lock = ref(require('../../assets/锁.png'));
const edit = ref(require('../../assets/试卷.png'));
const warning = ref(require('../../assets/错题集.png'));
const logout = ref(require('../../assets/退出.png'));
const arrows = ref(require('../../assets/箭头.png'));
// 菜单项数据
const menuItems = ref([
  { icon: activity, text: '激活题库' },
  { icon: user, text: '个人信息' },
  { icon: lock, text: '修改密码' },
  { icon: edit, text: '考试记录' },
  { icon: warning, text: '错题管理' },
  { icon: logout, text: '退出登录' }
])

// 微信登录处理
// 登录状态
const isLoggedIn = ref(false)
const userInfos = ref(null)

// 获取图标颜色
const getIconColor = (item) => {
  if (!isLoggedIn.value && item.text !== '激活题库') {
    return '#ccc' // 未登录时禁用项显示灰色
  }
  return '#07c160' // 正常状态显示绿色
}

// 微信登录处理
const handleLogin = () => {
  const wxRequest = config.wxPromisify(wx.request)
  Taro.getUserProfile({
    desc: '用于完善会员资料',
    success: async (res) => {
      const { encryptedData, iv, userInfo } = res
      console.log('用户信息:', userInfo.avatarUrl)
      const nickName = userInfo.nickName
      const avatarUrl = userInfo.avatarUrl
      const { code } = await Taro.login()
      const loginRes = await wxRequest({
        url: `${config.apiUrl}/login/judge`,
        method: 'POST',
        header: {
          'content-type': 'application/json'
        },
        data: { code, encryptedData, iv, nickName, avatarUrl }
      })
      if (loginRes.data.code === "0") {
        userInfos.value = { 'nickName':loginRes.data.data.nickName, 'avatarUrl':loginRes.data.data.avatarUrl}
        Taro.setStorageSync('token', loginRes.data.data.token)
        Taro.setStorageSync('id', loginRes.data.data.id)
        Taro.setStorageSync('userInfo', { nickName:loginRes.data.data.nickName, avatarUrl:loginRes.data.data.avatarUrl })
        isLoggedIn.value = true
      } else {
        Taro.showToast({ title: '登录失败', icon: 'none' })
      }
    },
    fail: (err) => {
      console.error('获取用户信息失败:', err)
      Taro.showToast({ title: '获取用户信息失败', icon: 'none' })
    }
  })
}

// 检查已有登录状态
const checkLoginStatus = () => {
  const token = Taro.getStorageSync('token')
  if (token) {
    isLoggedIn.value = true
    userInfos.value = Taro.getStorageSync('userInfo')
  }
}

// 页面加载时检查登录状态
onMounted(() => {
  checkLoginStatus()
})
// 页面挂载时就注册一次监听
Taro.eventCenter.on('userInfoUpdated', () => {
  // 重新从 Storage 取数据并刷新界面
  checkLoginStatus()          // 你的现成方法
})

// 也可以在组件卸载时注销
onUnmounted(() => {
  Taro.eventCenter.off('userInfoUpdated')
})
// 菜单项点击处理
const handleMenuClick = (item) => {
  console.log('点击菜单:', item.text)
  
  // 未登录时，只允许点击"激活题库"
  if (!isLoggedIn.value && item.text !== '激活题库') {
    Taro.showToast({
      title: '请先登录',
      icon: 'none'
    })
    return
  }

  if (item.text === '退出登录') {
    Taro.showModal({
      title: '确认退出',
      content: '确定要退出登录吗？',
      success: (res) => {
        if (res.confirm) {
          isLoggedIn.value = false
          userInfos.value = null
          Taro.clearStorageSync();
          Taro.showToast({ title: '已退出登录', icon: 'success' })
        }
      }
    })
  } else if(item.text === '个人信息'){
    Taro.navigateTo({
      url: '/pages/modifyPersonal/index'
    })
  } else if(item.text === '激活题库') {
    // 激活题库的逻辑
    Taro.showToast({
      title: '激活题库功能',
      icon: 'none'
    })
  } else if(item.text === '考试记录'){
    Taro.navigateTo({
      url: '/pages/examRecords/index'
    })
  }else if(item.text === '错题管理'){
    Taro.navigateTo({
      url: '/pages/errorManager/index'
    })
  }else if(item.text === '修改密码'){

  } else{
    // 其他菜单项的处理
    Taro.showToast({
      title: `${item.text}功能`,
      icon: 'none'
    })
  }
}
const activeTab = ref('profile')

const photoH = ref(require('../../assets/首页白.png'));
const photoP = ref(require('../../assets/个人中心绿.png'));
// 切换选项卡
const switchTab = (tabName) => {
  activeTab.value = tabName;
  if (tabName === 'index') {
    photoH.value = require('../../assets/首页绿.png');
    photoP.value = require('../../assets/个人中心白.png');
  } else if (tabName === 'profile') {
    photoH.value = require('../../assets/首页白.png');
    photoP.value = require('../../assets/个人中心绿.png');
  }
  // 这里可以添加页面跳转逻辑
  // navigator.push({
  //   url: `/pages/${tabName}/index`,
  // });
  // Taro.navigateTo ({
  //   url: `/pages/${tabName}/index`,
  // });
  Taro.redirectTo({
    url: `/pages/${tabName}/index`,
  });
}
</script>

<style lang="scss">
.page-container {
  // padding: 20px;
  background-color: #f5f5f5;
  height: 100%;
}

//微信登录按钮的外层容器
.login-container {
  background-color: #fff;
  height: calc(100vw * 0.56);
  border-radius: 12px;
  margin-bottom: 3%;
  display: flex;
  justify-content: center; // 水平居中
  align-items: center; // 垂直居中
  width: 100%; // 确保宽度铺满
}

.login-btn {
  background-color: #5a8dee;
  color: white;
  height: 90px;
  width: 80%; // 保持适当宽度
  border-radius: 12px;
  display: flex;
  justify-content: center; // 文字水平居中
  align-items: center; // 文字垂直居中
  font-size: 32px;
  font-weight: bold;
  margin: 0 auto; // 水平居中(额外保障)
}

.menu-list {
  background-color: #fff;
  border-radius: 12px;
  overflow: hidden;
  transition: all 0.3s ease;
}

.menu-list.disabled-menu {
  opacity: 0.8;
}

.menu-item {
  padding: 0 20px;
  transition: all 0.3s ease;
}

.menu-item.disabled-item {
  opacity: 0.6;
  pointer-events: none;
}

.menu-content {
  display: flex;
  align-items: center;
  height: 100px;
}

.menu-icon {
  width: 65px;
  margin-right: 20px;
}

.menu-text {
  flex: 1;
  font-size: 28px;
  color: #333;
  transition: color 0.3s ease;
}

.menu-text.disabled-text {
  color: #999;
}

.menu-arrow {
  width: 18px;
}

.divider {
  height: 1px;
  background-color: #f0f0f0;
  margin-left: 60px;
  /* 与图标对齐 */
}

/* 未登录提示样式 */
.login-tip {
  background-color: #fff;
  border-radius: 12px;
  padding: 30px;
  margin: 20px 0;
  text-align: center;
}

.tip-text {
  font-size: 28px;
  color: #666;
  display: block;
}

//顶部导航栏
/* 新增底部导航栏样式 */
.tab-bar {
  position: fixed; // 改为固定定位
  bottom: 0; // 固定在底部
  left: 0;
  right: 0;
  z-index: 100; // 确保在最上层

  // position: relative; /* 改为相对定位 */
  display: flex;
  height: 120px;
  background-color: #fff;
  box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.1);
  // margin-top: 20px; /* 与卡片区域间隔 */
  border-top-left-radius: 20px;
  border-top-right-radius: 20px;
  padding: 10px 0;
}

.tab-item {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;

  &.active {

    .tab-text,
    nut-icon {
      color: #07c160;
    }
  }

  nut-icon {
    margin-bottom: 8px;
    color: #666;
    font-size: 40px;
  }
}

.tab-text {
  font-size: 28px;
  color: #666;
  font-weight: normal;
}

.tab-icon {
  width: 40px;
  height: 40px;
  margin-bottom: 8px;
  transition: all 0.3s ease;
}

.tab-item.active .tab-icon {
  transform: scale(1.1); // 选中时轻微放大效果
}

//登录后的样式
.user-info {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 30px;
  background-color: #fff;
  border-radius: 12px;
  margin-bottom: 20px;
}

.avatar {
  width: 120px;
  height: 120px;
  border-radius: 50%;
  margin-bottom: 15px;
}

.nickname {
  font-size: 32px;
  color: #333;
  font-weight: bold;
}
</style>                                                        